package com.kc.gb.device.controller;

import com.kc.gb.device.tools.SSEStore;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.mvc.method.annotation.SseEmitter;

import javax.servlet.http.HttpServletRequest;
import java.io.IOException;

@Slf4j
@RestController
@RequestMapping("/station/refresh")
public class SSEAdminController {

    @GetMapping(value = "/sse", produces = MediaType.TEXT_EVENT_STREAM_VALUE)
    public SseEmitter sse(HttpServletRequest request,@RequestParam(required = false) String source) throws IOException {
        // POSTMAN 重新发起请求 SessionID 相同
        String sessionId = request.getSession().getId();
        SseEmitter emitter = new SseEmitter(1*60*1000L);
        log.info("SseEmitter created sessionId:{} hashcode:{} source:{}", sessionId,emitter.hashCode(),source);
        // 处理连接关闭
        emitter.onCompletion(() -> {
            try {
                SSEStore.removeEmitter(emitter);
                emitter.complete();
            } catch (Exception e) {
                log.info("SseEmitter complete sessionId:{} hashcode:{}", sessionId,emitter.hashCode(),e);
            }
        });
        // 处理服务器超时
        emitter.onTimeout(() -> {
            emitter.complete();
        });
        emitter.onError( callback->{
            emitter.complete();
        });
        SSEStore.addEmitter(emitter);
        return emitter;
    }
}
